<?php

namespace app\api\controller;

use app\api\exception\RegisterException;
use app\api\exception\ServiceException;
use think\Db;
use app\common\model\User;
use app\common\service\User as ServiceUser;
use EasyWeChat\Factory;

/**
 * 用户注册登录身份认证等的处理
 */
class Oauth extends Base
{

    /**
     * 通过微信获取用户的手机号
     *
     * @return void
     */
    public function getPhoneNumber()
    {
        $code = input('param.code/s', '');
        $app = Factory::miniProgram(config('wechat.mini'));
        $res = $app->phone_number->get($code);
        if ($res['errcode'] != 0) {
            return self::errors($res['errmsg']);
        } elseif (empty($res['phone_info'])) {
            return self::errors('获取失败');
        }

        return self::successs(['mobile' => $res['phone_info']['purePhoneNumber']], '获取手机号成功');
    }
    /**
     * 通过微信获取用户的openid
     *
     * @return void
     */
    public function getOpenid()
    {
        return self::successs(['openid' => '123456']);
        $code = input('param.code/s', '');
        $app = Factory::miniProgram(config('wechat.mini'));
        $res = $app->auth->session($code);
        if (!isset($res['openid'])) {
            return self::errors('登录失败，请重试');
        }


        return self::successs(['openid' => $res['openid']]);
    }


    /**
     * 用户注册
     *
     * @return void
     */
    public function register()
    {
        $data = input('post.', []);
        $data['nickname'] = '';
        $data['avatar'] = '';

        //数据验证
        $this->validate($data, 'User.register');

        Db::startTrans();
        try {
            //保存信息
            $service = new ServiceUser();
            $res = $service->register($data);
            if ($res['code'] != 1) {
                throw new ServiceException($res['msg']);
            }

            //自动登录
            $res2 = $service->login($res['data']['openid']);
            if ($res2['code'] != 1) {
                throw new ServiceException($res2['msg']);
            }
            Db::commit();
            return self::successs($res2['data'], '注册成功，并自动登录');
        } catch (RegisterException $e) {
            throw $e;
        } catch (ServiceException $e) {
            Db::rollback();
            return self::errors($e->getMessage());
        } catch (\Exception $e) {
            Db::rollback();
            recordExceptionInfo($e);
            return self::errors(config('app.app_debug') ? $e->getMessage() : '服务器错误');
        }
    }

    /**
     * 微信小程序登录
     *
     * @return void
     */
    public function login()
    {
        $code = input('post.code/s', '');
        if (empty($code)) {
            return self::errors('code有误');
        }
        try {
            $app = Factory::miniProgram(config('wechat.mini'));
            $res = $app->auth->session($code);
            if (!isset($res['openid'])) {
                return self::errors('登录失败，请重试');
            }

            $service = new ServiceUser();
            $res2 = $service->login($res['openid']);
            if ($res2['code'] != 1) {
                return self::errors($res2['msg']);
            }
            return self::successs($res2['data'], $res2['msg']);
        } catch (\Exception $e) {
            recordExceptionInfo($e);
            return self::errors(config('app.app_debug') ? $e->getMessage() : '服务器错误');
        }
    }
}
